'''
实现将图片批量导出到pdf
'''
import os
from PIL import Image, ImageOps
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def __create_temp_dir__(dir):
    if os.path.exists(dir) is False:
        os.mkdir(dir)
def images_to_pdf(image_folder, output_pdf):
    # 获取文件夹中的所有图片文件
    image_files = [f for f in os.listdir(image_folder)]

    # 创建PDF文件
    c = canvas.Canvas(output_pdf, pagesize=letter)
    width, height = letter
    for filename in image_files:
        if filename.endswith(('.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', '.BMP', '.tif', '.TIF', '.tiff', '.TIFF')):
            print('图片'+filename+'正在导入PDF中')
            image_path = os.path.join(image_folder, filename)
            # 打开图片并修正方向
            __create_temp_dir__(temp_folder)
            with Image.open(image_path) as image:
                # 检测并修正图片方向
                image = ImageOps.exif_transpose(image)
                # 保存修正后的图片到一个临时文件
                image_path = os.path.join(temp_folder, filename)
                image.save(image_path)
            img = Image.open(image_path)

            # 计算图片缩放比例，保持图片比例
            img_width, img_height = img.size
            aspect_ratio = img_width / img_height
            if aspect_ratio > width / (height - 40):  # 减去文字说明的高度
                img_width = width
                img_height = width / aspect_ratio
            else:
                img_height = height - 40  # 减去文字说明的高度
                img_width = (height - 40) * aspect_ratio

            # 计算图片的位置，使其居中
            img_x = (width - img_width) / 2
            img_y = (height - img_height - 20) / 2  # 减去文字说明的高度和间距

            # 将图片添加到PDF
            c.drawImage(image_path, img_x, img_y, width=img_width, height=img_height)

            # 添加图片名称作为文字说明，居中显示在图片上方
            c.setFont("Helvetica", 12)
            text = filename.split('.')[0]
            text_width = c.stringWidth(text, "Helvetica", 12)
            text_x = (width - text_width) / 2
            text_y = height - 20  # 文字说明的高度
            c.drawString(text_x, text_y, text)

            # 添加新页
            c.showPage()

    # 保存PDF文件
    c.save()

# 使用示例
image_folder = 'D:\Signorino'
temp_folder = image_folder + '_temp'
output_pdf = 'D:\\output.pdf'
images_to_pdf(image_folder, output_pdf)
